// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/exec/operator.h>
#include <pollux/exec/row_container.h>

namespace kumo::pollux::exec {
    class TopN : public Operator {
    public:
        TopN(
            int32_t operatorId,
            DriverCtx *driverCtx,
            const std::shared_ptr<const core::TopNNode> &topNNode);

        bool needsInput() const override {
            return !noMoreInput_;
        }

        void addInput(RowVectorPtr input) override;

        RowVectorPtr getOutput() override;

        void noMoreInput() override;

        BlockingReason isBlocked(ContinueFuture * /*future*/) override {
            return BlockingReason::kNotBlocked;
        }

        bool isFinished() override;

    private:
        const int32_t count_;

        bool finished_ = false;
        uint32_t numRowsReturned_ = 0;

        std::vector<column_index_t> sortingKeyColumns_;
        std::vector<column_index_t> nonKeyColumns_;

        // As the inputs are added to TopN operator, we use topRows_ (a priority
        // queue) to keep track of the pointers to rows stored in the
        // RowContainer (data_). We only update the RowContainer if a row is a
        // candidate for top rows. Otherwise, we will discard the row.
        // Since we use a priority queue for TopN, we perform
        // O(total_rows * logN) comparisons and require O(N) space.
        // Once all inputs are available, we copy the final set of rows to the
        // vector (rows_) in correct order. We use this vector along with the
        // RowContainer to generate the TopN's output.
        std::unique_ptr<RowContainer> data_;
        RowComparator comparator_;
        std::priority_queue<char *, std::vector<char *>, RowComparator> topRows_;
        std::vector<char *> rows_;

        std::vector<DecodedVector> decodedVectors_;
        vector_size_t outputBatchSize_;
    };
} // namespace kumo::pollux::exec
